from datetime import datetime

import pytest
from data.client_parkings import (
    create_client_parking_json,
    delete_client_parking,
    update_client_parking_json,
)
from data.clients import create_client_json
from data.models import ClientParking
from data.parkings import create_parking_json
from errors import Duplicate, Missing
from sqlalchemy import func


def test_create_client_parking(db):
    client = create_client_json(
        name="Alexander",
        surname="Ivanov",
        credit_card="1234123412341234",
        car_number="A000AA00",
    )
    parking = create_parking_json(
        address="Nevskiy pr.,1 ",
        opened=True,
        count_places=456,
        count_available_places=123,
    )

    time_in = datetime.now()
    client_parking = create_client_parking_json(
        client_id=client["id"], parking_id=parking["id"], time_in=time_in
    )

    assert client_parking["client_id"] == client["id"]
    assert client_parking["parking_id"] == parking["id"]
    assert client_parking["time_in"] == time_in
    assert client_parking["time_out"] is None
    assert db.session.query(func.count(ClientParking.id)).scalar() == 1


def test_create_client_parking_duplicate():
    with pytest.raises(Duplicate):
        create_client_parking_json(client_id=1, parking_id=1)


def test_create_client_parking_wrong_client_id():
    with pytest.raises(Missing):
        create_client_parking_json(client_id=123, parking_id=1)


def test_create_client_parking_wrong_parking_id():
    with pytest.raises(Missing):
        create_client_parking_json(client_id=1, parking_id=123)


def test_update_client_parking(db):
    time_out = datetime.now()
    result = update_client_parking_json(client_id=1, parking_id=1, time_out=time_out)
    assert result["time_out"] == time_out
    cp_from_db: ClientParking = (
        db.session.query(ClientParking).where(ClientParking.id == result["id"]).scalar()
    )
    assert cp_from_db.time_out == time_out


def test_delete_client_parking(db):
    delete_client_parking(client_id=1, parking_id=1)
    count = db.session.query(func.count(ClientParking.id)).scalar()
    assert count == 0


def test_delete_client_parking_wrong_ids():
    with pytest.raises(Missing):
        delete_client_parking(client_id=123, parking_id=456)
